package com.example.studytest.Controller.Researcher;

import com.example.studytest.Entity.Admin.Admin;
import com.example.studytest.Entity.Researcher.T_researcher;
import com.example.studytest.Entity.Test4.Test4_record;
import com.example.studytest.Entity.User.T_invite;
import com.example.studytest.Entity.User.T_user;
import com.example.studytest.Repository.Researcher.T_researcherRepository;
import com.example.studytest.Repository.Test4.Aural_recordRespository;
import com.example.studytest.Repository.User.T_inviteRepository;
import com.example.studytest.Repository.User.T_userRepository;
import com.example.studytest.Util.CreateSheetUtil;
import com.example.studytest.Util.MailUtil;
import com.example.studytest.Util.PingYinUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.sql.Timestamp;

import static com.example.studytest.Util.MailUtil.sendMail;

@RestController
@RequestMapping("/researcher")
public class ResearcherController {

    @Autowired
    private T_researcherRepository researcherRepository;

    @Autowired
    private T_inviteRepository t_inviteRepository;

    @Autowired
    private Aural_recordRespository aural_recordRespository;

    @Autowired
    private T_userRepository t_userRepository;

    //生成邀请码
    private List<Object> inviteList;

    //    自助激活邮箱
    @PostMapping("/register")
    public T_researcher Register(@RequestBody T_researcher t_researcher){
        //生成用户code
        String code = UUID.randomUUID().toString().replace("-", "");
        t_researcher.setActivate_code(code);

        //添加用户
        T_researcher result = researcherRepository.save(t_researcher);
        sendMail(result.getEmail(),result.getActivate_code());

        //向用户发送激活邮件
//        MailUtil.sendMail(t_researcher.getEmail(),t_researcher.getActivate_code(),"TALL-激活注册");

        return result;
    }

    @PostMapping("/ResetPwd_send")
    public String ResetPwd_send(@RequestBody Map<String, Object> map){
        String r_email = (String)map.get("r_email");
        System.out.println("-------PassEmailAction.sendResetEmail-----------" + r_email);
        T_researcher researcher_cur = researcherRepository.findByEmail(r_email);
        if(researcher_cur!=null){
            String v_code = String.valueOf((int)((Math.random()*9+1)*100000));
            researcherRepository.UpdateVerification_code(v_code,researcher_cur.getEmail());

//            Timestamp outDate = new Timestamp(System.currentTimeMillis() + 10 * 60 * 1000);// 10分钟后过期
//            Long date = outDate.getTime() / 1000 * 1000;// 忽略毫秒数  mySql 取出时间是忽略毫秒数的
            sendResetCodetoMail(r_email, v_code);
            return "Mail sent successfully";
        }else {
            return "User name does not exist";
        }
    }

    @PostMapping("ResetPwd_check")
    public String ResetPwd_check(@RequestBody Map<String, Object> map){
        String r_email = (String)map.get("r_email");
        String v_code1 = (String)map.get("v_code");
        String n_pwd = (String)map.get("n_pwd");
        String v_code2 = researcherRepository.findVcodeByEmail(r_email);
        System.out.println("v_1:"+v_code1);
        System.out.println("v_2:"+v_code2);

        if (v_code1.equals(v_code2)){
            researcherRepository.UpdatePwd(n_pwd,r_email);
            return "Your password has been modified successfully";
        }else{
            return "The verification code is incorrect, please re-enter";
        }
    }


    public static boolean sendMail(String to, String code) {

        try {
            Properties props = new Properties();
            props.put("username", "tall-webtest@foxmail.com");
            props.put("password", "vhzxvmkevzsufbca");
            props.put("mail.transport.protocol", "smtp" );
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.port", "25" );

            Session mailSession = Session.getDefaultInstance(props);

            Message msg = new MimeMessage(mailSession);
            msg.setFrom(new InternetAddress("tall-webtest@foxmail.com"));
            msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            msg.setSubject("TALL Researcher Account Activating Registration");
            msg.setContent("<h1>Please click on the link below to complete the activation process.</h1>" +
                    "<h3>Click <a href='https://www.tall-webtest.cn/studytest-0.0.1-SNAPSHOT/researcher/activate?code="+code+"'>here</a> to activate.</h3>","text/html;charset=UTF-8");
//            msg.setContent("<h1>此邮件为官方激活邮件！请点击下面链接完成激活操作！</h1>","text/html;charset=UTF-8");
            msg.saveChanges();

            Transport transport = mailSession.getTransport("smtp");
            transport.connect(props.getProperty("mail.smtp.host"), props
                    .getProperty("username"), props.getProperty("password"));
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return false;
        }
        return true;
    }


    public static  boolean sendResetCodetoMail(String to, String code){
        try {
            Properties props = new Properties();
            props.put("username", "tall-webtest@foxmail.com");
            props.put("password", "vhzxvmkevzsufbca");
            props.put("mail.transport.protocol", "smtp" );
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.port", "25" );

            Session mailSession = Session.getDefaultInstance(props);

            Message msg = new MimeMessage(mailSession);
            msg.setFrom(new InternetAddress("tall-webtest@foxmail.com"));
            msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            msg.setSubject("TALL Researcher Account Reset Password Email Verification");
            msg.setContent("<h1>You are resetting your password. The verification code is "+ code+". Do not disclose the verification code to others. This verification code is valid for 10 minutes.</h1>","text/html;charset=UTF-8");
//            msg.setContent("<h1>此邮件为官方激活邮件！请点击下面链接完成激活操作！</h1>","text/html;charset=UTF-8");
            msg.saveChanges();

            Transport transport = mailSession.getTransport("smtp");
            transport.connect(props.getProperty("mail.smtp.host"), props
                    .getProperty("username"), props.getProperty("password"));
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return false;
        }
        return true;
    }

    /**
     * 激活用户
     * @param code 用户激活码
     * @return 是否激活成功
     */

    @GetMapping("/activate")
    public Boolean Active(@Param("code")String code){
        String email=researcherRepository.findEmailByCode(code);
        System.out.println(email);
        if(email!=null && email!=""){
            //如果存在用户，将此用户状态设为可用
            researcherRepository.SetState(email);
            return true;
        }else{
            return false;
        }
    }




    //研究者登录
    @GetMapping("/login{email}/{pwd}")
    public Map<String,Object> findByCode(@PathVariable String email, @PathVariable String pwd)
    {
        System.out.println(email);
        System.out.println(pwd);
        Map<String, Object> map =new HashMap<>();
        //通过账户进行查找
        T_researcher researcher = researcherRepository.findByEmail(email);

        System.out.println(researcher);
        //如果账户存在
        if(!ObjectUtils.isEmpty(researcher))
        {
            //如果密码也相等
            if(researcher.getPwd().equals(pwd))
            {
                map.put("state",true);
                map.put("researcher",researcher);
                map.put("msg","登录成功！");
            }
            //密码不等
            else{
                map.put("state",false);
                map.put("msg","密码错误！");
            }

        }
        else{
            map.put("state",false);
            map.put("msg","账户错误！");
        }
        return map;

    }

    //随机数生成
    public static String getRandomCharacterAndNumber(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

            if ("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
                // int choice = 97; // 指定字符串为小写字母
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
            {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    //研究者生成邀请码和测试链接
    @PostMapping("/generateCode_Link")
    public String generateCode_Link(@RequestBody Map<String, Object> map){
        System.out.println("进入");
        //获取前端传入的具体描述和邀请码数量
        String r_email = (String)map.get("r_email");
        String modality = (String)map.get("modality"); //aural(A) or wriiten(W)
        Integer num = (Integer)map.get("num");
//        String link = "https://www.tall-webtest.cn/#/BeforeTest";
        String link = "";

        if(modality.equals("aural") || modality.equals("A")){
            link = "https://www.tall-webtest.cn/#/BeforeLogin";
        }
        else {
            link = "https://www.tall-webtest.cn/written/#/BeforeLogin";
        }

        //生成固定位数的随机数组，这里固定10位，可修改
        //<String> randomCode = RandomUtil.getDistinctRandom(10,num);

        //生成并存储，效率问题待优化
        inviteList = new ArrayList<Object>();
        try{
            for(int i = 0; i < num; i++){
                T_invite t_invite = new T_invite();
                String ramdomCode = getRandomCharacterAndNumber(6);
                t_invite.setR_email(r_email);
                t_invite.setCode(ramdomCode+Integer.toString(i));
//                t_invite.setDes(des);
                t_invite.setSession(modality);
                t_invite.setTest_link(link);
                inviteList.add(t_invite);
                t_inviteRepository.save(t_invite);
            }
            return "success";
        }
        catch (Exception e){
            System.out.println(e);
            return "failure";
        }
    }

    //下载研究生邀请码以及测试链接
    @GetMapping("/downloadCode_Link")
    public void downloadCode(HttpServletResponse response){

        String sheetName = "invite_code";
        String[] heads = {"id","code","r_email","modality","test_link"};
        XSSFWorkbook xssfWorkbook = CreateSheetUtil.createXSSFWorkbook(sheetName,heads,inviteList);

        //保存文件
        String fileName = "invite_code.xlsx";
        OutputStream outputStream = null;

        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
            //设置ContentType请求信息格式
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断email是否注册
    @GetMapping("/findAllByEmail{email}")
    public T_researcher findAllByEmail(@PathVariable("email") String email) {
        //如果t_user表中不存在这个邮箱，那么可以登录
        return researcherRepository.findAllByEmail(email);

    }

    //下载研究者相关被测者音频
    @GetMapping("/send_records/{remail}")
    public List<Test4_record> send_records(@PathVariable("remail") String remail){
        //List<Test4_record> results =  aural_recordRespository.findAllByDateIs(date);
        List<Test4_record> results =  aural_recordRespository.findByRemail(remail);
        if(results.isEmpty()){
            System.out.println(" results are null");
        }
        //System.out.println(results);

        return results;
    }



}
